package basics;

import pixi.core.display.Container;


class SceneManager {

	public static var instance:SceneManager = new SceneManager();

	private var _sceneStack:Array<GameState>;
	private var _currentState:GameState;

	@:isVar public var root(get, set):Container;

	function get_root():Container {
		return root;
	}

	function set_root(value:Container):Container {
		return this.root = value;
	}

	private function new() {
		_sceneStack = new Array<GameState>();
    }

	public function runState(state:GameState){
		if(_sceneStack.length == 0){
			state.onEnter();
			_sceneStack.push(state);
			this.root.addChild(state);
		}else{
			trace("只能执行第一个场景");
		}
	}

	public function changeState(state:GameState):Void{
		if(state == null){
			return;
		}

		var lastState = _sceneStack.pop();
		if(lastState != null){
			lastState.onExit();
			this.root.removeChild(lastState);
		}

		state.onEnter();
		_sceneStack.push(state);
		this.root.addChild(state);
	}

	public function pushState(state:GameState):Void{
		if(state == null){
			return;
		}

		state.onEnter();
		_sceneStack.push(state);
		this.root.addChild(state);
	}

	public function popState():Void{
		var state = _sceneStack.pop();
		if(state != null){
			state.onExit();
			this.root.removeChild(state);
		}
	}

	public function onUpdate(dt:Float):Void{
		for(state in _sceneStack){
			state.onUpdate(dt);
		}
	}
}
